package com.xinchao.job.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.xinchao.common.bo.DeviceReportBO;
import com.xinchao.common.constant.CacheConstant;
import com.xinchao.core.cache.redis.RedisCacheDao;
import com.xinchao.job.service.asynccomment.AsyncCommentService;

@Service("syncDeviceInfoJobService")
public class SyncDeviceInfoJobService  {
	private static Logger logger = LoggerFactory.getLogger(SyncDeviceInfoJobService.class);
	@Autowired
	private RedisCacheDao redisCacheDao;
	@Autowired
	private AsyncCommentService asyncCommentService;
	@Value("${xc.device.report.time.redundancy}")
    private Integer redundancyTime;
	@Value("${xc.device.report.cache.hash.size}")
    private Integer hashEntrySize;
	public void sync() {
		
		// 存放数据时平均放到了${hashEntrySize}个桶中，取出对应的设备信息同步到数据库中;将超时仍未上报信息的终端缓存移除
		long currentTime = System.currentTimeMillis();
		long count = 0L;
		for (int i=0;i<hashEntrySize;i++) {
			try {
				Map<Object, Object> devices = redisCacheDao.getAllCache(CacheConstant.CACHE_NAME_DEVICE_REPORT_PREFIX + i);
				if ( devices!= null ) {
					List<Object> cacheList = new ArrayList<>(devices.values());
					List<DeviceReportBO> reports = new ArrayList<>();
					DeviceReportBO  temp = null;
					
					for (Object o : cacheList) {
						temp = (DeviceReportBO) o;
						// 超过3分钟未上报的终端不再进行同步
						if ( temp.getLastReportTime() + 180*1000 > currentTime ) {
							reports.add(temp);
						} 
					}
					
					if (CollectionUtils.isNotEmpty(reports)) { 
						count += reports.size();
						asyncCommentService.batchSyncDeviceReport(reports);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("批量同步设备信息到数据库异常：" + e.getMessage(),e);
			}
		}
		logger.info("当前同步终端状态数量：" + count);
	}
	
	
}
